
import Foundation

private var lastClickTimeKey: Void?

extension UIButton {
    /// 设置按钮的防连点时间间隔
    /// - Parameter interval: 时间间隔（秒）
    func preventDoubleClick(interval: TimeInterval = 1.0) {
        // 添加点击事件（移除已有的点击事件，防止重复添加）
        removeTarget(self, action: #selector(preventDoubleClickAction), for: .touchUpInside)
        addTarget(self, action: #selector(preventDoubleClickAction), for: .touchUpInside)
        
        // 存储时间间隔
        objc_setAssociatedObject(self,
                                &lastClickTimeKey,
                                interval,
                                .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        
        // 设置是否可以点击
        isEnabled = true
    }
    
    @objc private func preventDoubleClickAction() {
        isEnabled = false
        
        // 获取时间间隔
        let interval = objc_getAssociatedObject(self, &lastClickTimeKey) as? TimeInterval ?? 1.0
        
        // 延迟启用按钮
        DispatchQueue.main.asyncAfter(deadline: .now() + interval) { [weak self] in
            self?.isEnabled = true
        }
    }
}
